package com.diamondsys.embrapa;

import com.diamondsys.embrapa.util.JsfUtil;
import com.diamondsys.embrapa.util.JsfUtil.PersistAction;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;


@Named("sigifEventosintController")
@SessionScoped
public class SigifEventosintController implements Serializable {

    @EJB
    private com.diamondsys.embrapa.SigifEventosintFacade ejbFacade;
    private List<SigifEventosint> items = null;
    private SigifEventosint selected;
    private TbInst selectedCliente;

    //Data Inicial
    private Date dateFrom;
    private Date dateTo;

    public Date getDateFrom() {
        return dateFrom;
    }

    public void setDateFrom(Date dateFrom) {
        this.dateFrom = dateFrom;
    }

    public Date getDateTo() {
        return dateTo;
    }

    public void setDateTo(Date dateTo) {
        this.dateTo = dateTo;
    }
    
    public boolean filterByDate(Object value, Object filter, Locale locale) {
        boolean ret=true;
        
        String filterText = (value == null) ? null : value.toString().trim();
        if (filterText == null || filterText.isEmpty()) {
            return true;
        }
        
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        Date filterDate;

        try {
            filterDate = df.parse(filterText);

            if (dateFrom != null && dateFrom.after(filterDate)) ret = false;
            if (dateTo != null && dateTo.before(filterDate)) ret = false;

        } catch (ParseException e) {
            return true;
        }

       return ret;
    } 

    //Filtro Data Final
    private Date dateFromFim;
    private Date dateToFim;

    public Date getDateFromFim() {
        return dateFrom;
    }

    public void setDateFromFim(Date dateFromFim) {
        this.dateFromFim = dateFromFim;
    }

    public Date getDateToFim() {
        return dateToFim;
    }

    public void setDateToFim(Date dateToFim) {
        this.dateToFim = dateToFim;
    }
    
    public boolean filterByDateFim(Object value, Object filter, Locale locale) {
        boolean ret=true;
        
        String filterText = (value == null) ? null : value.toString().trim();
        if (filterText == null || filterText.isEmpty()) {
            return true;
        }
        
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        Date filterDate;

        try {
            filterDate = df.parse(filterText);

            if (dateFromFim != null && dateFromFim.after(filterDate)) ret = false;
            if (dateToFim != null && dateToFim.before(filterDate)) ret = false;

        } catch (ParseException e) {
            return true;
        }

       return ret;
    } 
    
    public SigifEventosintController() {
    }

    public SigifEventosint getSelected() {
        return selected;
    }

    public void setSelected(SigifEventosint selected) {
        this.selected = selected;
    }

    protected void setEmbeddableKeys() {
    }

    protected void initializeEmbeddableKey() {
    }

    private SigifEventosintFacade getFacade() {
        return ejbFacade;
    }

    public SigifEventosint prepareCreate() {
        selected = new SigifEventosint();
        initializeEmbeddableKey();
        return selected;
    }

    public void create() {
        persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("SigifEventosintCreated"));
        if (!JsfUtil.isValidationFailed()) {
            items = null;    // Invalidate list of items to trigger re-query.
        }
    }

    public void update() {
        persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("SigifEventosintUpdated"));
    }

    public void destroy() {
        persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("SigifEventosintDeleted"));
        if (!JsfUtil.isValidationFailed()) {
            selected = null; // Remove selection
            items = null;    // Invalidate list of items to trigger re-query.
        }
    }

    public List<SigifEventosint> getItems() {
        if (selectedCliente != null) items = getFacade().findByClienteId(selectedCliente);
        else items = getFacade().findAll();
        return items;
    }

    private void persist(PersistAction persistAction, String successMessage) {
        if (selected != null) {
            setEmbeddableKeys();
            try {
                if (persistAction != PersistAction.DELETE) {
                    getFacade().edit(selected);
                } else {
                    getFacade().remove(selected);
                }
                JsfUtil.addSuccessMessage(successMessage);
            } catch (EJBException ex) {
                String msg = "";
                Throwable cause = ex.getCause();
                if (cause != null) {
                    msg = cause.getLocalizedMessage();
                }
                if (msg.length() > 0) {
                    JsfUtil.addErrorMessage(msg);
                } else {
                    JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
                }
            } catch (Exception ex) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            }
        }
    }

    public SigifEventosint getSigifEventosint(java.lang.Integer id) {
        return getFacade().find(id);
    }

    public List<SigifEventosint> getItemsAvailableSelectMany() {
        return getFacade().findAll();
    }

    public List<SigifEventosint> getItemsAvailableSelectOne() {
        return getFacade().findAll();
    }

    /**
     *
     */
    public List<SigifEventosint> getEventoDia() {
        return getFacade().getEntityManager().createNamedQuery("SigifEventosint.findByDatIniVig", SigifEventosint.class)
                .setParameter("datIniVig", new Date())
                .getResultList();
    }

    /**
     * @return the selectedCliente
     */
    public TbInst getSelectedCliente() {
        return selectedCliente;
    }

    /**
     * @param selectedCliente the selectedCliente to set
     */
    public void setSelectedCliente(TbInst selectedCliente) {
        this.selectedCliente = selectedCliente;
    }

    public String customFormatDate(Date date) {
        return JsfUtil.customFormatDate(date);
    }    
    
    @FacesConverter(forClass = SigifEventosint.class)
    public static class SigifEventosintControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            SigifEventosintController controller = (SigifEventosintController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "sigifEventosintController");
            return controller.getSigifEventosint(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof SigifEventosint) {
                SigifEventosint o = (SigifEventosint) object;
                return getStringKey(o.getIdeventosint());
            } else {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), SigifEventosint.class.getName()});
                return null;
            }
        }

    }

}
